package com.cxx.controller;

import com.cxx.log.Log;
import com.cxx.pojo.Admin;
import com.cxx.pojo.Result;
import com.cxx.pojo.User;
import com.cxx.service.UserService;
import com.cxx.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/person-web/api/*")
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;
    //注册为普通用户
    @PostMapping("/regist")
    @Log
    public Result regist(@RequestBody User user){
        Integer stastus=userService.regist(user);
        if(stastus==1){
            return Result.sucess("WAIT-APPROVE");
        } else if (stastus==0) {
            return Result.error("EXISTED");
        }else {
            return Result.error("ERROR");
        }
    }
    @PostMapping("/login")
    @Log
    public Result login(@RequestBody User user){
        Map<String,Object> claims=new HashMap<>();
        //管理员校验
        Admin selectAdmin=userService.adminExist(user.getUserName(),user.getUserPassword());
        if(selectAdmin!=null){
            claims.put("id",user.getId());
            claims.put("name",user.getUserName());
            claims.put("status",user.getStatus());
            claims.put("type","admin");
            String jwt= jwtUtils.generateJwt(claims);
            return Result.sucess(jwt);
        }
        //普通用户校验
        else {
            User selectUser=userService.exist(user.getUserName(),user.getUserPassword());
            if(selectUser!=null&&selectUser.getApprove()==0){
                return Result.error("NOT-APPROVE");
            }
            if(selectUser!=null&&selectUser.getStatus()==0){
                System.out.println(selectUser.getStatus());
                return Result.error("FORBIDEN");
            }
            if(selectUser!=null&&selectUser.getApprove()==1){
                claims.put("id",user.getId());
                claims.put("name",user.getUserName());
                claims.put("status",user.getStatus());
                claims.put("type","user");
                String jwt= jwtUtils.generateJwt(claims);
                return Result.sucess(jwt);
            }
        }
        return Result.error("INFO-ERROR");
    }
}
